<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司星级" prop="companyLevel">
        <el-input
          v-model="queryParams.companyLevel"
          placeholder="请输入公司星级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工厂类别" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择">
          <el-option
            v-for="item in categoryOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:marks:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:marks:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:marks:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:marks:add']"
          icon="el-icon-upload2"
          size="mini"
          type="info"
          @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:marks:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="marksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号"  width="68"  type="index"/>
      <el-table-column label="公司名称" align="center" prop="companyName"/>
      <el-table-column label="公司简介" align="center" prop="companyProfile" :show-overflow-tooltip="true"/>
      <el-table-column label="公司星级" align="center" prop="companyLevel">
        <template slot-scope="scope">
          <el-rate v-model="scope.row.companyLevel" disabled></el-rate>
        </template>
      </el-table-column>
      <el-table-column label="坐标经纬度" align="center" prop="longitude">
        <template slot-scope="scope">
          <span>{{ scope.row.longitude }}</span>,
          <span>{{ scope.row.latitude }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工厂类别" align="center" prop="categoryId">
        <template slot-scope="scope">
          <span>{{ scope.row.categoryId |formatCategory(categoryOptions2)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:marks:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:marks:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改企业管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称"/>
        </el-form-item>
        <el-form-item label="公司简介" prop="companyProfile">
          <el-input v-model="form.companyProfile" placeholder="请输入公司简介"/>
        </el-form-item>
        <el-form-item label="公司星级" prop="companyLevel">
          <el-rate v-model="form.companyLevel" style="position: relative;top: 6px"></el-rate>
        </el-form-item>
        <el-form-item label="工厂类别" prop="categoryId">
          <treeselect v-model="form.categoryId"   :disable-branch-nodes="true" :options="categoryOptions"  placeholder="请选择工厂类别" />
        </el-form-item>
        <el-form-item label="公司地址经度" prop="longitude">
          <el-input v-model="form.longitude" disabled />
        </el-form-item>
        <el-form-item label="公司地址纬度" prop="longitude">
          <el-input v-model="form.latitude" disabled/>
          <el-button type="primary" size="mini" @click="handleChoicePosition">选择公司经纬度</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="importUpload.title"
      :visible.sync="importUpload.open"
      append-to-body
      width="400px"
    >
      <el-upload
        ref="upload"
        :action="importUpload.url"
        :auto-upload="false"
        :disabled="importUpload.isUploading"
        :headers="importUpload.headers"
        :limit="1"
        :on-progress="handleImportFileUploadProgress"
        :on-success="handleImportFileSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          <el-button size="mini" type="primary" @click="importTemplate">
            下载模板<i class="el-icon-download el-icon--right"></i>
          </el-button>
          <div style="color: red; display: inline">
            提示：仅允许导入“xls”或“xlsx”格式文件！
          </div>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="importUpload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--显示经纬度-->
    <el-dialog title="经纬度选择"  :visible.sync="openPosition" width="80%" append-to-body>
      <div class="mapBox" style="width: 100%;height: 70vh">
        <div class="left">
          <Map1 v-if="openPosition" style="width: 100%;height: 100%" @showPosition="showPosition" ref="childMap"></Map1>
        </div>
        <div class="right">
          <el-form ref="form2" :model="form2" :rules="rules2" label-width="120px">
            <el-form-item label="定位名称" prop="positionName">
              <el-input v-model="form2.positionName" placeholder="请输入定位名称"/>
              <el-button type="primary" size="mini" @click="handleSelectPosition">确定</el-button>
            </el-form-item>
            <el-form-item label="当前选择经度" prop="longitude">
              <el-input v-model="form2.longitude" disabled/>
            </el-form-item>
            <el-form-item label="当前选择纬度" prop="latitude">
              <el-input v-model="form2.latitude" disabled/>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMarks, getMarks, delMarks, addMarks, updateMarks } from '@/api/system/marks'
import Map1 from '@/components/Map1'
import { getToken } from '@/utils/auth'
import { getCityCode } from '@/utils/utils'
import { getTreeSelect, listCategory } from '@/api/system/category'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

let vm = {};
export default {
  name: 'index',
  components: {
    Map1,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业管理表格数据
      marksList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        companyProfile: null,
        companyLevel: null,
        longitude: null,
        latitude: null,
        categoryId: null,
        categoryParentId:7,
      },
      // 表单参数
      form: {},
      //当前类别id
      parentId:1,
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        companyLevel: [
          { required: true, message: "公司星级不能为空", trigger: "blur" }
        ],
        companyProfile: [
          { required: true, message: "公司简介不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "工厂类别不能为空", trigger: "blur" }
        ],
        longitude: [
          { required: true, message: "坐标经度不能为空", trigger: "blur" }
        ],
        latitude: [
          { required: true, message: '坐标纬度不能为空', trigger: 'blur' }
        ]
      },
      rules2: {
        longitude: [
          { required: true, message: '坐标经度不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '坐标纬度不能为空', trigger: 'blur' }
        ]
      },
      importUpload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/marks/importData",
      },
      //显示经纬度
      openPosition: false,
      form2: {
        //定位名称
        positionName: null,
        longitude:null,
        latitude:null,
      },
      //工厂类别 -- 格式化
      categoryOptions:[],
      //工厂类别 -- 未格式化
      categoryOptions2:[]
    }
  },

  created() {
    this.getList();
    //获取格式化后的类别
    getTreeSelect().then(res => {
      this.categoryOptions = [];
      this.categoryOptions = res.data.filter(item => item.id == this.queryParams.categoryParentId)
      this.categoryOptions = this.categoryOptions[0].children
      console.log(this.categoryOptions,"this.categoryOptions")
    })
    // 获取未格式化类别
    listCategory().then(res => {
      this.categoryOptions2 = [];
      this.categoryOptions2 = res.data
    })
  },
  computed:{

  },
  filters:{
    formatCategory:function(id,categoryOptions2){
      const a =  categoryOptions2.filter(item => {
        return id== item.categoryId
      })
      return a[0].categoryName
    }
  },
  methods: {
    // 文件上传中处理
    handleImportFileUploadProgress(event, file, fileList) {
      this.$refs.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleImportFileSuccess(response, file, fileList) {
      this.importUpload.open = false;
      this.importUpload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.loading_const.close();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    importTemplate(){
      const  fileName = "现代建筑产业信息表制造业.xlsx"
      this.download('system/marks/importTemplate', {
        fileName
      }, fileName)
    },
    openLoading() {
      this.loading_const = this.$loading({
        lock: true,
        text: "导入时间较长,请耐心等待。",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
        customClass: "loading_area",
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.openLoading();
      this.$refs.upload.submit();
    },
    //导入企业
    handleImport() {
      this.importUpload.title = "企业批量导入";
      this.importUpload.open = true;
    },
    /** 查询企业管理列表 */
    getList() {
      this.loading = true;
      listMarks(this.queryParams).then(response => {
        this.marksList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮 -- 经纬度
    cancel2() {
      this.openPosition = false;
      this.form2 = {
        positionName:null,
        longitude: null,
        latitude: null,
      };
      this.resetForm("form2");
    },
    // 表单重置
    reset() {
      this.form = {
        marksId: null,
        companyName: null,
        companyProfile: null,
        companyLevel: null,
        longitude: null,
        latitude: null,
        categoryId: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.marksId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 转换企业类别数据结构 */
    normalizer(node) {
      console.log(node,"node")
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children
      };
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const marksId = row.marksId || this.ids
      this.$router.push({
        path: "/marks/details",
        query: {
          marksId,
          categoryParentId: this.queryParams.categoryParentId
        }
      });
      // getMarks(marksId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改企业管理";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.marksId != null) {
            updateMarks(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMarks(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const marksIds = row.marksId || this.ids;
      this.$modal.confirm('是否确认删除企业管理编号为"' + marksIds + '"的数据项？').then(function() {
        return delMarks(marksIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/marks/export', {
        ...this.queryParams
      }, `marks_${new Date().getTime()}.xlsx`)
    },
    /** 选择经纬度*/
    handleChoicePosition() {
      this.openPosition = true
      this.form2.longitude = this.form.longitude
      this.form2.latitude = this.form.latitude
      console.log(this.form2,"this.form2")
      //获取经纬度转换为的cityCode
      if(this.form2.longitude && this.form2.latitude){
        getCityCode(this.form2.longitude,this.form2.latitude).then(response => {
          this.form2.positionName = response.regeocode.formatted_address
          this.handleSelectPosition()
        })
      }
    },
    //地图查询定位
    handleSelectPosition() {
      this.$refs.childMap.searchPosition(this.form2.positionName)
    },
    //显示经纬度
    showPosition(x, y,code) {
      this.form2.longitude = x
      this.form2.latitude = y
      this.form.cityCode = code
    },
    //确认选择经纬度
    submitForm2() {
      this.$refs["form2"].validate(valid => {
          if (valid) {
            this.form.longitude = this.form2.longitude
            this.form.latitude = this.form2.latitude
            this.openPosition = false
          }
        }
      )
    },
  }
};
</script>
<style scoped lang="scss">
.mapBox {
  display: flex;

  .left {
    flex: 2;
    height: 70vh;
    border: 2px solid #ccc;
  }

  .right {
    flex: 1;
    margin-left: 20px;
    height: 70vh;
  }
}
</style>


